﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Utils.Helper
{
    public class ExpressionHelper
    {

        private static bool ResolveAnd(string left, string right, string[] codes)
        {
            return Resolve(left, codes) && Resolve(right, codes);
        }

        private static bool ResolveOr(string left, string right, string[] codes)
        {
            return Resolve(left, codes) || Resolve(right, codes);
        }

        private static string Unboxing(string expression)
        {
            int level = 0;
            for (int i = 0; i < expression.Length; i++)
            {
                char c = expression[i];
                if (c == '(')
                {
                    level++;
                }
                else if (c == ')')
                {
                    level--;
                    if (level == 0)
                    {
                        if (i == expression.Length - 1)
                            return expression.Substring(1, expression.Length - 1);
                        return expression;
                    }
                }
            }
            if (level != 0) throw Error.SystemError("括号没有成对出现");
            return expression;
        }

        /// <summary>
        /// 解析表达式
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="codes"></param>
        /// <returns></returns>

        public static bool Resolve(string expression, string[] codes)
        {
            expression = expression.Trim();
            if (expression.IndexOf('(') == 0)
            {
                expression = Unboxing(expression);
            }
            if (expression.Contains("|") || expression.Contains("&"))
            {
                int level = 0;
                for (int i = 0; i < expression.Length; i++)
                {
                    char c = expression[i];
                    if (c == '(')
                    {
                        level++;
                    }
                    else if (c == ')')
                    {
                        level--;
                        continue;
                    }
                    if (level == 0)
                    {
                        if (c == '|')
                        {
                            return ResolveOr(expression.Substring(0, i), expression.Substring(i + 1), codes);
                        }
                        else if (c == '&')
                        {
                            return ResolveAnd(expression.Substring(0, i), expression.Substring(i + 1), codes);
                        }
                    }
                }
            }
            return codes.Contains(expression);
        }

    }
}
